package controller;

import model.Role;
import model.User;
import service.RoleService;
import service.UserService;
import service.impl.RoleServiceImpl;
import service.impl.UserServiceImpl;
import util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(urlPatterns = "/power/user/users")
public class UsersServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("select".equals(method)) {
            select(req, resp);
        } else if ("addUser".equals(method)) {
            addUser(req, resp);
        } else if ("selectById".equals(method)) {
            selectById(req, resp);
        } else if ("update".equals(method)) {
            update(req, resp);
        } else if ("updateById".equals(method)) {
            updateById(req, resp);
        } else if ("deleteById".equals(method)) {
            deleteById(req, resp);
        }

    }

    //查询数据（分页）
    protected void select(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PageUtil pageUtil = new PageUtil();
        //1. 接收分页参数和模糊查询参数
        String index = req.getParameter("index");
        int pageIndex = (index == null || index.length() == 0) ? 1 : Integer.parseInt(index);
        //2. 调取service方法(1. 查询数据列表2. 查询总条数的方法)
        List<User> userList = userService.getUsers(pageIndex, pageUtil.getPageSize());
        int total = userService.total();
        pageUtil.setTotal(total);
        pageUtil.setPageIndex(pageIndex);
        pageUtil.setDateList(userList);

        //3. 存值跳转
        req.setAttribute("pi", pageUtil);
        req.getRequestDispatcher("list.jsp").forward(req, resp);

    }

    //添加用户
    protected void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String realname = req.getParameter("realname");
        String sex = req.getParameter("sex");
        String roleId = req.getParameter("roleId");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String idNumber = req.getParameter("idNumber");
        String info = req.getParameter("info");
        User user = new User();
        user.setLoginName(username);
        user.setPassWord(password);
        user.setRealName(realname);
        user.setSex(Integer.parseInt(sex));
        user.setEmail(email);
        user.setAddress(address);
        user.setPhone(phone);
        user.setCardId(idNumber);
        user.setInfo(info);
        user.setRoleId(Integer.parseInt(roleId));
        int i = userService.addUser(user);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        String contextPath = req.getContextPath();
        if (i > 0) {
            writer.println("<script>alert('新增成功');location.href='" + contextPath + "/power/user/users?method=select'</script>");
        } else {
            writer.println("<script>alert('新增失败');location.href='" + contextPath + "/power/user/users?method=select'</script>");
        }
    }

    //查询用户详细信息
    protected void selectById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userid = req.getParameter("userid");
        User user = userService.getUserById(Integer.parseInt(userid));
        RoleService roleService = new RoleServiceImpl();
        List<Role> role = roleService.getRole();
        req.setAttribute("user", user);
        req.setAttribute("role", role);
        req.getRequestDispatcher("info.jsp").forward(req, resp);
    }

    protected void updateById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userid = req.getParameter("userid");
        User user = userService.getUserById(Integer.parseInt(userid));
        RoleService roleService = new RoleServiceImpl();
        List<Role> role = roleService.getRole();
        req.setAttribute("user", user);
        req.setAttribute("role", role);
        req.getRequestDispatcher("edit.jsp").forward(req, resp);
    }

    //更新
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        String contextPath = req.getContextPath();
        //获取参数
        String userid = req.getParameter("userid");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String realname = req.getParameter("realname");
        String sex = req.getParameter("sex");
        String roleId = req.getParameter("roleId");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String idNumber = req.getParameter("idNumber");
        String info = req.getParameter("info");
        //封装对象
        User user = new User();
        user.setUserId(Integer.parseInt(userid));
        user.setLoginName(username);
        user.setPassWord(password);
        user.setRealName(realname);
        user.setSex(Integer.parseInt(sex));
        user.setEmail(email);
        user.setAddress(address);
        user.setPhone(phone);
        user.setCardId(idNumber);
        user.setInfo(info);
        user.setRoleId(Integer.parseInt(roleId));
        //调用service方法
        int update = userService.update(user);
        if (update > 0) {
            writer.println("<script>alert('更新成功');location.href='" + contextPath + "/power/user/users?method=select'</script>");
        } else {
            writer.println("<script>alert('更新失败');location.href='" + contextPath + "/power/user/users?method=select'</script>");
        }
    }

    protected void deleteById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        String contextPath = req.getContextPath();
        String userid = req.getParameter("userid");
        int update = userService.delete(Integer.parseInt(userid));
        if (update > 0) {
            writer.println("<script>alert('删除成功');location.href='" + contextPath + "/power/user/users?method=select'</script>");
        } else {
            writer.println("<script>alert('删除失败');location.href='" + contextPath + "/power/user/users?method=select'</script>");
        }
    }

}
